package com.example.mr5.mygame.main;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;

import android.widget.ArrayAdapter;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;


import com.example.mr5.mygame.R;
import com.example.mr5.mygame.gameBattleCity.BattleCity;
import com.example.mr5.mygame.utils.AdID;
import com.example.mr5.mygame.utils.NetWorkConnection;
import com.example.mr5.mygame.utils.SharePreferenceUtil;
import com.example.mr5.mygame.webGame.WebGame;
import com.example.mr5.mygame.game2048.Game2048Activity;
import com.example.mr5.mygame.gameCatchCat.CatchCatActivity;
import com.example.mr5.mygame.gameFrogge.FroggeActivity;
import com.example.mr5.mygame.gameQuzhiChess.QuZhiChess;
import com.example.mr5.mygame.modle.Game;
import com.example.mr5.mygame.main.ad.AdAcitivty;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.waps.AppConnect;
import cn.waps.UpdatePointsListener;

public class MainActivity extends Activity implements AdapterView.OnItemClickListener, UpdatePointsListener, View.OnClickListener {

    private ListView homeList;
    private TextView point, earnScore;
    private HomeListAdapter homeListAdapter;
    private HomeGridViewAdapter homeGridViewAdapter;
    private List<Game> netGameList;
    private List<Game> localGameList;
    private List<String> nameList;
    private List<String> summaryList;

    private List<String> localGameName;
    private List<String> localGameSummary;
    protected GridView localGrid;
    private GridLayout header;
    private int[] localIcon = new int[]{
            R.drawable.ic_2048, R.drawable.ic_catch_cat,
            R.drawable.ic_frog, R.drawable.ic_qu_chess, R.drawable.tanke};
    private int[] netIcon = new int[]{
            R.drawable.ic_yibihua, R.drawable.ic_super_ranseti,
            R.drawable.ic_more};

    private ImageView barBack, more;
    private TextView barTitle;
    NetWorkConnection conUtil = new NetWorkConnection(this);
    SharePreferenceUtil util;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

        setContentView(R.layout.activity_main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.bar);

        if (conUtil.isConnection()) {
            AppConnect.getInstance("95cec2974bd7db4551fc275772d992a9", AdID.ID, this);
            AppConnect.getInstance(this);
            AppConnect.getInstance(this).getPoints(this);
            AppConnect.getInstance(this).initUninstallAd(this);
            AppConnect.getInstance(this).awardPoints(500);
            initSetting();
        } else {
            new AlertDialog.Builder(MainActivity.this).setTitle("你好")
                    .setMessage("网络连接失败，请检查好网络连接后再重新开启")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    }).setNegativeButton("单机模式", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    initSettingSingleModel();
                }
            }).show();
        }
    }

    private void initSetting() {
        util = new SharePreferenceUtil(this);
        if (util.getisFirst()) {
            util.setBiggistNum(1024);
            if (util.getShowAd().equals("yes")) {
                new AlertDialog.Builder(MainActivity.this).setTitle("你好")
                        .setMessage("首次启动，赠送您30积分！")
                        .setPositiveButton("立即领取", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                AppConnect.getInstance(MainActivity.this).awardPoints(50);
                            }
                        }).show();
            }

            util.setIsFirst(false);
        }
        String showAd = AppConnect.getInstance(this).getConfig("showAd", "yes");
        util.setShowAd(showAd);
        String costScore1 = AppConnect.getInstance(this).getConfig("costScore1", "100");
        util.setCostScore1(costScore1);
        String costScore2 = AppConnect.getInstance(this).getConfig("costScore2", "30");
        util.setCostScore2(costScore2);

        initView();
    }

    private void initSettingSingleModel() {
        util = new SharePreferenceUtil(this);
        if (util.getisFirst()) {
            util.setBiggistNum(1024);
            util.setIsFirst(false);
        }
        util.setShowAd("no");
//        String costScore1 = AppConnect.getInstance(this).getConfig("costScore1", "100");
//        util.setCostScore1(costScore1);
//        String costScore2 = AppConnect.getInstance(this).getConfig("costScore2", "30");
//        util.setCostScore2(costScore2);

        initView();
    }

    private void initView() {
        barBack = (ImageView) findViewById(R.id.header_left_btn);
        barBack.setVisibility(View.GONE);
        more = (ImageView) findViewById(R.id.more);
        more.setVisibility(View.VISIBLE);
        more.setOnClickListener(this);
        barTitle = (TextView) findViewById(R.id.header_text);
        barTitle.setText(getTitle());

        header = (GridLayout) findViewById(R.id.header);
        if (util.getShowAd().equals("no")) {
            header.setVisibility(View.GONE);
        }
        localGrid = (GridView) findViewById(R.id.local_game_gridview);
        point = (TextView) findViewById(R.id.point);
        earnScore = (TextView) findViewById(R.id.earn_score);
        homeList = (ListView) findViewById(R.id.home_list);
        netGameList = new ArrayList<Game>();
        localGameList = new ArrayList<Game>();
        initData();
        homeListAdapter = new HomeListAdapter(this, netGameList);
        homeGridViewAdapter = new HomeGridViewAdapter(this, localGameList);
        localGrid.setAdapter(homeGridViewAdapter);
        homeList.setAdapter(homeListAdapter);
        homeList.setOnItemClickListener(this);
        localGrid.setOnItemClickListener(this);
        earnScore.setOnClickListener(this);

    }

    private void initData() {

        nameList = Arrays.asList(getResources().getStringArray(R.array.net_game_name));
        summaryList = Arrays.asList(getResources().getStringArray(R.array.game_summary));

        localGameName = Arrays.asList(getResources().getStringArray(R.array.local_game_name));
        localGameSummary = Arrays.asList(getResources().getStringArray(R.array.local_game_summary));

        Game game;
        for (int i = 0; i < nameList.size(); i++) {
            game = new Game();
            game.setName(nameList.get(i));
            game.setSummary(summaryList.get(i));
            game.setIcon(netIcon[i]);
            game.setNeedNet(true);
            netGameList.add(game);
        }

        for (int i = 0; i < localGameName.size(); i++) {
            game = new Game();
            game.setName(localGameName.get(i));
            game.setSummary(localGameSummary.get(i));
            game.setIcon(localIcon[i]);
            game.setNeedNet(false);
            localGameList.add(game);

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(MainActivity.this, WebGame.class);
        if (parent.getId() == R.id.local_game_gridview) {
            switch (position) {
                case 0:
                    startActivity(new Intent(MainActivity.this, Game2048Activity.class));
                    break;
                case 1:
                    startActivity(new Intent(MainActivity.this, CatchCatActivity.class));
                    break;
                case 2:
                    startActivity(new Intent(MainActivity.this, FroggeActivity.class));
                    break;
                case 3:
                    startActivity(new Intent(MainActivity.this, QuZhiChess.class));
                    break;
                case 4:
                    if (util.getFistBattleGame() && util.getShowAd().equals("yes")) {

                        new AlertDialog.Builder(this).setTitle("你好").setMessage("解锁该游戏需要消耗" + Integer.parseInt(util.getCostScore1()) + "积分,是否继续？")
                                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (conUtil.isConnection()) {
                                            SharePreferenceUtil util = new SharePreferenceUtil(MainActivity.this);
                                            if (util.getScore() >= Integer.parseInt(util.getCostScore1())) {
                                                util.setScore(util.getScore() - Integer.parseInt(util.getCostScore1()));
                                                costScore(Integer.parseInt(util.getCostScore1()));
                                                util.setFirstBattleGame(false);
                                                startActivity(new Intent(MainActivity.this, BattleCity.class));
                                            } else {
                                                new AlertDialog.Builder(MainActivity.this).setTitle("你好")
                                                        .setMessage("您当前积分不足，是否前往赚取积分？")
                                                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                                            @Override
                                                            public void onClick(DialogInterface dialog, int which) {
                                                                Game2048Activity.getMainActivity().gotoEarnScore();
                                                            }
                                                        }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                    }
                                                }).show();
                                            }
                                        } else
                                            Toast.makeText(MainActivity.this, "请检查网络连接", Toast.LENGTH_LONG).show();
                                    }
                                }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
                    } else if(util.getShowAd().equals("no")){
                        new AlertDialog.Builder(MainActivity.this).setTitle("你好")
                                .setMessage("该游戏需在网络模式下运行")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                }).show();
                    }else {
                        startActivity(new Intent(MainActivity.this, BattleCity.class));
                    }
                    break;
            }
        } else {
            switch (position) {
                case 0://一笔画
                    intent.putExtra("url", "http://www.7pul.com/game/oneLineDraw/");
                    startActivity(intent);
                    break;
                case 1:
                    intent.putExtra("url", "http://www.7pul.com/game/cjrst/");
                    startActivity(intent);
                    break;
                case 2:
                    if (util.getShowAd().equals("no")) {
                        intent.putExtra("url", " http://www.iaibi.com/");
                        startActivity(intent);
                    } else
                        AppConnect.getInstance(this).showOffers(this);
                    break;
            }
        }
    }

    public void costScore(int score) {
        AppConnect.getInstance(this).spendPoints(score);
    }

    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_window, null);
        // 设置按钮的点击事件
//        Button button = (Button) contentView.findViewById(R.id.button1);
        TextView about_score = (TextView) contentView.findViewById(R.id.pop_about_score);
        if (util.getShowAd().equals("no")) {
            about_score.setVisibility(View.GONE);
        }
        about_score.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivity.this).setTitle("关于积分")
                        .setMessage("1.积分的作用？\n      积分可用于游戏通关\n" +
                                "2.如何赚取积分？\n        点击首页的“赚取积分”或“更多游戏”，进入任务列表，按提示完成任务即可获得相应积分。")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).setNegativeButton("赚取积分", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AppConnect.getInstance(MainActivity.this).showAppOffers(MainActivity.this);
                    }
                }).show();
            }

        });
        TextView about_us = (TextView) contentView.findViewById(R.id.pop_about_us);
        about_us.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivity.this).setTitle("关于我们")
                        .setMessage("如您对并应用有任何意见或建议（如希望增加哪些休闲游戏等），请通过邮件联系我们。\n邮箱：1129114667@qq.com.\n更多有趣应用请从 \n http://mr555.apps.cn \n 进行下载，感谢您的使用！")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).show();
            }

        });

        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                Log.i("mengdd", "onTouch : ");

                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.pop_background));

        // 设置好参数之后再show
        popupWindow.showAsDropDown(view);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (conUtil.isConnection()) {
            AppConnect.getInstance(this).close();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (conUtil.isConnection()) {
            AppConnect.getInstance(this).getPoints(this);
        }
    }

    @Override
    public void getUpdatePoints(final String s, final int i) {
        Log.e("aaa", s + i);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //更新UI
                point.setText("我的" + s + ":" + i);
            }
        });

        util.setScore(i);
    }

    @Override
    public void getUpdatePointsFailed(String s) {
        Log.e("bbb", s);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.more) {
            showPopupWindow(v);

        } else
            AppConnect.getInstance(this).showOffers(this);
//        startActivity(new Intent(MainActivity.this, AdAcitivty.class));
    }

    long time = 0;

    @Override
    public void onBackPressed() {
        if (time == 0) {
            time = System.currentTimeMillis();
            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_LONG).show();
        } else {
            if (System.currentTimeMillis() - time <= 2000) {
                finish();
                System.exit(0);
            } else {
                time = 0;
            }
        }

    }
}
